package com.zw.stock_sell_storage.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zw.stock_sell_storage.dto.MyPageDto;
import com.zw.stock_sell_storage.dto.PermissionDto;
import com.zw.stock_sell_storage.dto.RoleDto;
import com.zw.stock_sell_storage.dto.ex.RoleDtoEx;
import com.zw.stock_sell_storage.mapper.RoleMapper;
import com.zw.stock_sell_storage.service.IPermissionService;
import com.zw.stock_sell_storage.service.IRoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
@Service
public class RoleServiceImpl extends ServiceImpl<RoleMapper, RoleDto> implements IRoleService {
    @Autowired
    RoleMapper roleMapper;
    @Autowired
    IPermissionService iPermissionService;
    @Override
    public Page<RoleDto> queryRoleList(MyPageDto<RoleDto> myPageDto) {

        return roleMapper.selectPage(new Page<>(myPageDto.getCurrentPage(),myPageDto.getPageSize()),null);
    }

    @Override
    public List<RoleDto> queryRoleByUserId(int userId) {

        return roleMapper.selectRoleByUserId(userId);
    }

    @Override
    @Transactional
    public boolean addRole(RoleDtoEx roleDtoEx) {
        roleMapper.insert(roleDtoEx);
        roleMapper.insertRoleLinkPermission(roleDtoEx);
        return true;
    }

    @Override
    @Transactional
    public boolean rmvRole(int roleId) {
        roleMapper.deleteRoleLinkPermission(roleId);
        roleMapper.deleteById(roleId);
        return true;
    }

    @Override
    public RoleDtoEx queryRoleById(int roleId) {
        RoleDto roleDto = roleMapper.selectById(roleId);
        List<RoleDto> roleList = new ArrayList<>();
        roleList.add(roleDto);
        List<PermissionDto> permissionList = iPermissionService.queryPermissionByUserId(roleList);
        RoleDtoEx roleDtoEx = new RoleDtoEx();
        roleDtoEx.setRoleId(roleDto.getRoleId());
        roleDtoEx.setRoleName(roleDto.getRoleName());
        roleDtoEx.setPermissionList(permissionList);
        return roleDtoEx;
    }

    @Override
    public boolean updateRole(RoleDtoEx roleDtoEx) {
        roleMapper.deleteRoleLinkPermission(roleDtoEx.getRoleId());
        roleMapper.insertRoleLinkPermission(roleDtoEx);
        return true;
    }

    @Override
    public List<RoleDto> queryAllRole() {
        return roleMapper.selectList(null);
    }
}
